﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"heap.h"
void HeapInit(Heap* hp)//初始化
{
	assert(hp);
	hp->a = NULL;
	hp->capacity = 0;
	hp->size = 0;
}
void HeapDestroy(Heap* hp)//销毁
{
	assert(hp);
	if (hp->a != NULL)
	{
		free(hp->a);
		hp->a = NULL;
		hp->size = 0;
		hp->capacity = 0;
	}

}
void Swap(HPDatatype* p1, HPDatatype* p2)
{
	HPDatatype tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
void AdjustUP(HPDatatype *a, int child)//向上调整
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HeapPush(Heap* hp, HPDatatype x)//插入
{
	assert(hp);
	if (hp->size == hp->capacity)
	{
		HPDatatype newcapacity = hp->capacity == 0 ? 4 : 2 * hp->capacity;
		HPDatatype* tmp =(HPDatatype*) realloc(hp->a, sizeof(HPDatatype) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc");
			return;
		}
		hp->a = tmp;
		hp->capacity = newcapacity;
	}
	hp->a[hp->size] = x;
	hp->size++;
	AdjustUP(hp->a, hp->size - 1);
}
bool HeapEmpty(Heap* hp)
{
	assert(hp);
	return hp->size == 0;
}
void AdjustDown(HPDatatype* a, int n, int parent)//向下调整
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child+1<n && a[child + 1] < a[child])
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void HeapPop(Heap* hp)//删除堆顶元素；
{
	assert(hp);
	assert(!HeapEmpty(hp));
	Swap(&hp->a[0], &hp->a[hp->size - 1]);
	hp->size--;
	AdjustDown(hp->a,hp->size,0);

}
HPDatatype HeapTop(Heap* hp)//取出堆顶元素；
{
	assert(hp);
	assert(!HeapEmpty(hp));
	return hp->a[0];
}
int HeapSize(Heap* hp)//个数
{
	assert(hp);
	return hp->size;
}